const router = require('express').Router()
const { createSuccess, createFail } = require('../utils')
const { insertUser, userLogin } = require('../models/user')
const checkUserRegister = require('../middlewares/checkUserRegister')
const checkUserLogin = require('../middlewares/checkUserLogin')
const getUserInfo = require('../middlewares/getUserInfo')

router.post('/register', checkUserRegister, (req, res) => {
  const { username, password } = req.body
  insertUser(username, password)
    .then(() => {
      res.json(createSuccess())
    })
    .catch((err) => {
      res.json(createFail(err))
    })
})

router.post('/login', checkUserLogin, (req, res) => {
  const { username, password } = req.body
  userLogin(username, password)
    .then((result) => {
      if (result.length === 0) {
        res.json(createFail('用户名或密码错误'))
      } else {
        const [user] = result
        const userInfo = { id: user.id, username: user.username }
        req.session.userInfo = userInfo
        res.json(createSuccess(userInfo))
      }
    })
    .catch((err) => {
      console.log(err)
      res.json(createFail('数据库异常'))
    })
})

router.post('/userInfo', getUserInfo, (req, res) => {
  if (req.user) {
    const { id, username, role, gender } = req.user
    res.json({
      id,
      username,
      role,
      gender
    })
  } else {
    res.json(createFail('没有该用户信息'))
  }
})

router.get('/logout', (req, res) => {
  req.session.destroy((err) => {
    if (err) {
      res.json(createFail('不合法的session，请重新登录'))
    } else {
      res.json(createSuccess('退出成功'))
    }
  })
})

module.exports = router
